package com.gable.exhibition.service.impl;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.ChineseToEnglish;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.*;
import com.gable.exhibition.init.ItemInIt;
import com.gable.exhibition.init.MaintainerManufacturerInit;
import com.gable.exhibition.init.ManufacturerInit;
import com.gable.exhibition.init.SupplierManufacturerInit;
import com.gable.exhibition.model.*;
import com.gable.exhibition.service.UpkeepService;
import com.gable.exhibition.service.UserService;
import com.gable.exhibition.thread.*;
import com.gable.exhibition.util.InsideOutsideUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import com.gable.exhibition.websocket.WSClientManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lesson on 2018/2/25.
 */
@Service("upkeepService")
public class UpkeepServiceImpl implements UpkeepService {

    @Value("${upkeepByPlatform1}")
    String upkeepByPlatform1;       //申请保养推送给平台短信URL

    @Value("${upkeepByService1}")
    String upkeepByService1;        //分配服务商短信URL

    @Value("${upkeepByEngineer1}")
    String upkeepByEngineer1;       //分配服务商工程师短信URL

    @Value("${upkeepByPlatform2}")
    String upkeepByPlatform2;       //保养未通过推送给平台短信URL

    @Value("${upkeepByService2}")
    String upkeepByService2;        //保养通过推送给服务商短信URL

    @Value("${upkeepByHospital2}")
    String upkeepByHospital2;       //保养处理给医院的短信URL

    @Value("${upkeepByHospital1}")
    String upkeepByHospital1;       //保养工程师预计到场短信URL

    @Value("${webSocket_InsertUpkeepUrl}")
    String webSocket_InsertUpkeepUrl;   //保养流程创建群组

    @Value("${webSocket_endRepairUrl}")
    String webSocket_endRepairUrl;      //保养流程结束解散群组

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    UpkeepDao upkeepDao;

    @Autowired
    EventDao eventDao;

    @Autowired
    HospitalDao hospitalDao;

    @Autowired
    ManufacturerMaintainerDao manufacturerMaintainerDao;

    @Autowired
    FileDao fileDao;

    @Autowired
    MaintainerDao maintainerDao;

    @Autowired
    UserDao userDao;

    @Autowired
    DeviceDao deviceDao;

    @Autowired
    PartDao partDao;

    @Autowired
    AppointDao appointDao;

    @Autowired
    UserService userService;

    @Autowired
    MaintainerManufacturerInit maintainerManufacturerInit;

    @Autowired
    ManufacturerInit manufacturerInit;


    @Override
    public ReturnResultUtil queryUpkeepList(UpkeepView upkeepView) {
        int count = upkeepDao.queryUpkeepCount(upkeepView);
        List<UpkeepView> list = upkeepDao.queryUpkeepList(upkeepView);
        list = queryCurrentService(list);
        UpkeepView upkeepView1 = new UpkeepView();
        upkeepView1.setCount(count);
        upkeepView1.setList(list);
        return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,upkeepView1);
    }


    public List<UpkeepView>  queryCurrentService(List<UpkeepView> upkeepList){
        for(UpkeepView up : upkeepList){
            if(up.getAppointList() != null && up.getAppointList().size() > 0){
                Long instructedType = up.getAppointList().get(0).getInstructedType();
                Long instructedId = up.getAppointList().get(0).getInstructedId() == null ? 0L : up.getAppointList().get(0).getInstructedId();
                if(instructedType != null){
                    String serviceName = "";
                    if(instructedType.longValue() == 1105 ){
                        serviceName = SupplierManufacturerInit.supplierManufacturerMap.get(instructedId).getSupplierName();
                    }else if(instructedType.longValue() == 1102 ){
                        serviceName = ManufacturerInit.manufacturerMaintainerMap.get(instructedId).getManufacturerName();
                    }else if(instructedType.longValue() == 1103 ){
                        serviceName = MaintainerManufacturerInit.maintainerManufacturerMap.get(instructedId).getMaintainerName();
                    }
                    up.setHospitalServiceName(serviceName);
                }
            }else{
                up.setHospitalServiceName(up.getServiceName());
            }
        }
        return upkeepList;
    }



    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil addUpkeep(UpkeepView upkeepView,Integer hospital_user) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        upkeepView.setUpkeepId(UUIDGenerator.getUniqueLong());
        //upkeepView.setUpkeepDate(df.format(new Date()));
        String upkeepNo = "BY"+UUIDGenerator.getUniqueLong();
        upkeepView.setUpkeepNo(upkeepNo);
        upkeepView.setStatus(1800L);
        upkeepView.setCreateTime(df.format(new Date()));
        Long servieType = upkeepView.getServiceType() == null || upkeepView.getServiceType() == 0 ? null : upkeepView.getServiceType();
        upkeepView.setServiceType(servieType);
        upkeepView.setIsDel(0);
        int result = upkeepDao.insertSelective(upkeepView);
        if(result > 0){
            if(upkeepView.getDeviceStatus() != null){
                Device device = new Device();//修改设备状态
                device.setDeviceStatus(upkeepView.getDeviceStatus());
                device.setDeviceId(upkeepView.getDeviceId());
                deviceDao.updateByPrimaryKeySelective(device);
            }

            UpkeepView upkeepView1 = upkeepDao.queryUpkeepInfo(upkeepView);

            //插入保养事件信息
            Event event1 = new Event();
            event1.setEventId(UUIDGenerator.getUniqueLong());
            event1.setEventDateTime(df.format(new Date()));
            event1.setEventTitle("申请保养");

            String str = "";
            Long serviceType = upkeepView1.getServiceType();
            if(serviceType == null && hospital_user == 0){
                str = upkeepView1.getUpkeepApplicant() + "申请的" + upkeepView1.getDeviceName() + "保养，待平台指派";
            }else if(serviceType != null){
                String serviceName = upkeepView.getServiceName();
                if(serviceType == 1102 ){
                    serviceName = ManufacturerInit.manufacturerMaintainerMap.get(upkeepView1.getServiceId()).getManufacturerName();
                }else if(serviceType == 1105){
                    serviceName = SupplierManufacturerInit.supplierManufacturerMap.get(upkeepView1.getServiceId()).getSupplierName();
                }
                str += upkeepView1.getUpkeepApplicant() + "-申请的" + upkeepView1.getDeviceName() + "保养并安排了服务商-"+ serviceName;

                if(hospital_user == 1){
                    str  += "安排了工程师"+ upkeepView1.getEngineerNames()+",电话：" + upkeepView1.getMobiles()+","
                            +"待平台处理";
                }
            }
            event1.setEventContent(str);
            event1.setKeyType(1602L);
            event1.setKeyId(upkeepView.getUpkeepId());
            event1.setCreatePerson(upkeepView.getCreatePerson());
            event1.setCreateTime(df.format(new Date()));
            event1.setIsDel(0);
            eventDao.insertSelective(event1);

            //插入设备事件信息
            Event event = new Event();
            event.setEventId(UUIDGenerator.getUniqueLong());
            event.setEventDateTime(df.format(new Date()));
            event.setEventContent("设备申请保养");
            event.setEventTitle("设备保养");
            event.setKeyType(1701L);
            event.setCreatePerson(upkeepView.getCreatePerson());
            event.setCreateTime(df.format(new Date()));
            event.setIsDel(0);
            event.setKeyId(upkeepView.getDeviceId());
            eventDao.insertSelective(event);




            Thread t = new Thread(new Runnable() { //socket 推送
                @Override
                public void run() {
                    try {
                        sendUkeepMessageBySocket(upkeepView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();

            new Thread(new ChatGroupThread(upkeepView.getUpkeepId()+"",webSocket_InsertUpkeepUrl)).start();

            String hospitalName = upkeepView1.getHospitalName();
            String deviceName = upkeepView1.getDeviceName();
            String sn = upkeepView1.getSn();

            new Thread(new RepairSendSmsThread(hospitalName,deviceName,sn,userDao,null,upkeepByPlatform1)).start();

            return new ReturnResultUtil(200,MessageUtil.APPLYUPKEEPSUCCESS,upkeepView.getUpkeepId());
        }

        return new ReturnResultUtil(500,MessageUtil.APPLYUPKEEPEXCEPTION);
    }


    public String queryServiceName(Long serviceType,Long serviceId){
        String serviceName = "";
        if(serviceType!= null){
            if(serviceType.longValue() == 1102){
                serviceName = ManufacturerInit.manufacturerMaintainerMap.get(serviceId).getManufacturerName();
            }else if(serviceType.longValue() == 1105){
                serviceName = SupplierManufacturerInit.supplierManufacturerMap.get(serviceId).getSupplierName();
            }else if(serviceType.longValue() == 1103){
                serviceName = MaintainerManufacturerInit.maintainerManufacturerMap.get(serviceId).getMaintainerName();
            }
        }
        return serviceName;
    }

    public String queryServiceTypeName(Long serviceType){
        String serviceTypeName = "平台";
        if(serviceType == null){
            return serviceTypeName;
        }
        if(serviceType.longValue() == 1102){
            serviceTypeName = "厂家";
        }else if(serviceType.longValue() == 1105){
            serviceTypeName = "经销商";
        }else if(serviceType.longValue() == 1103){
            serviceTypeName = "维修商";
        }else{
            serviceTypeName="";
        }
        return serviceTypeName;
    }

    @Override
    public ReturnResultUtil queryUpkeepInfo(UpkeepView upkeepView) {
        UpkeepView detail = upkeepDao.queryUpkeepInfo(upkeepView);
        if(detail.getServiceType() != null){
            if(detail.getServiceType().longValue() == 1105 || detail.getServiceType().longValue() == 1102){
                String serviceName= "";
                String serviceContacts = "";
                String servicePhone = "";
                if(detail.getServiceType().longValue() == 1105 ){
                    serviceName = SupplierManufacturerInit.supplierManufacturerMap.get(detail.getServiceId()).getSupplierName();
                    serviceContacts = SupplierManufacturerInit.supplierManufacturerMap.get(detail.getServiceId()).getMasterContacts();
                    servicePhone = SupplierManufacturerInit.supplierManufacturerMap.get(detail.getServiceId()).getMasterPhone();
                }
                if(detail.getServiceType().longValue() == 1102 ){
                    serviceName = ManufacturerInit.manufacturerMaintainerMap.get(detail.getServiceId()).getManufacturerName();
                    serviceContacts = ManufacturerInit.manufacturerMaintainerMap.get(detail.getServiceId()).getMasterContacts();
                    servicePhone = ManufacturerInit.manufacturerMaintainerMap.get(detail.getServiceId()).getMasterPhone();
                }
                detail.setServiceName(serviceName);
                detail.setServiceContacts(serviceContacts);
                detail.setServicePhone(servicePhone);
            }
        }

        if(detail.getAppointList() != null && detail.getAppointList().size() > 0){
            int count = 0;
            for(AppointView av  : detail.getAppointList()){
                count++;
                if(av.getInstructType() != null ){
                    av.setInstructTypeName(ItemInIt.itemMapByItemId.get(av.getInstructType()).getItem());
                    String instructName = "";
                    long instructId = av.getInstructId() == null ? 0L : av.getInstructId().longValue();
                    if(av.getInstructType().longValue() == 1102){
                        instructName = ManufacturerInit.manufacturerMaintainerMap.get(instructId).getManufacturerName();
                    }else if(av.getInstructType().longValue() == 1105){
                        instructName = SupplierManufacturerInit.supplierManufacturerMap.get(instructId).getSupplierName();
                    }else if(av.getInstructType().longValue() == 1103){
                        instructName = MaintainerManufacturerInit.maintainerManufacturerMap.get(instructId).getMaintainerName();
                    }
                    av.setInstructName(instructName);
                }else{
                    av.setInstructName("平台");
                }
                if(av.getInstructedType() != null){
                    av.setInstructedTypeName(ItemInIt.itemMapByItemId.get(av.getInstructedType()).getItem());
                    String instructName = "";
                    long instructedId = av.getInstructedId() == null ? 0L : av.getInstructedId().longValue();
                    if(av.getInstructedType().longValue() == 1102){
                        instructName = ManufacturerInit.manufacturerMaintainerMap.get(instructedId).getManufacturerName();
                    }else if(av.getInstructedType().longValue() == 1105){
                        instructName = SupplierManufacturerInit.supplierManufacturerMap.get(instructedId).getSupplierName();
                    }else if(av.getInstructedType().longValue() == 1103){
                        instructName = MaintainerManufacturerInit.maintainerManufacturerMap.get(instructedId).getMaintainerName();
                    }
                    av.setInstructedName(instructName);
                }

                String instructTypeName = queryServiceTypeName(av.getInstructType());
                String instructedTypeName = queryServiceTypeName(av.getInstructedType());
                av.setInstructTypeName(instructTypeName);
                av.setInstructedTypeName(instructedTypeName);

                if(count == detail.getAppointList().size()){
                    AppointView  appoint =  av;
                    detail.setAppointView(appoint);
                }
            }
        }
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,detail);
    }

    @Override
    public ReturnResultUtil assignServiceInit(Long upkeepId) {
        UpkeepInitServiceView uisv = upkeepDao.assignServiceInit(upkeepId);

        if(uisv.getUpkeepView().getServiceType() == null || (uisv.getUpkeepView().getExamine() != null && uisv.getUpkeepView().getExamine() == 0)){
            uisv.setFlag(1);  //flag = 1 时  医院报修没有选择服务商。
        }else if(uisv.getUpkeepView().getServiceType().longValue() == 1105 || uisv.getUpkeepView().getServiceType().longValue() == 1102){
            uisv.setFlag(2); //flag == 2 时，医院报修选择的厂商或者是供应商
            String serviceName= "";
            String serviceContacts = "";
            String servicePhone = "";
            if(uisv.getUpkeepView().getServiceType().longValue() == 1105 ){
                serviceName = SupplierManufacturerInit.supplierManufacturerMap.get(uisv.getUpkeepView().getServiceId()).getSupplierName();
                serviceContacts = SupplierManufacturerInit.supplierManufacturerMap.get(uisv.getUpkeepView().getServiceId()).getMasterContacts();
                servicePhone = SupplierManufacturerInit.supplierManufacturerMap.get(uisv.getUpkeepView().getServiceId()).getMasterPhone();
            }
            if(uisv.getUpkeepView().getServiceType().longValue() == 1102 ){
                serviceName = ManufacturerInit.manufacturerMaintainerMap.get(uisv.getUpkeepView().getServiceId()).getManufacturerName();
                serviceContacts = ManufacturerInit.manufacturerMaintainerMap.get(uisv.getUpkeepView().getServiceId()).getMasterContacts();
                servicePhone = ManufacturerInit.manufacturerMaintainerMap.get(uisv.getUpkeepView().getServiceId()).getMasterPhone();
            }
            uisv.getUpkeepView().setServiceName(serviceName);
            uisv.getUpkeepView().setServiceContacts(serviceContacts);
            uisv.getUpkeepView().setServicePhone(servicePhone);
        }else if(uisv.getUpkeepView().getServiceType().longValue() == 1103){
            uisv.setFlag(3); //flag == 3 时,医院报修选择的是维修商，需要审核

        }
        if(uisv.getEnableTime() != null && !uisv.getEnableTime().equals("") && (uisv.getDeviceWarrantyPeriod() != null || uisv.getSupplierWarrantyPeriod() != null)){
            Long value = InsideOutsideUtil.queryWarranty(uisv.getEnableTime(),uisv.getDeviceWarrantyPeriod(),uisv.getSupplierWarrantyPeriod());
            uisv.setDevicePaoneAbroad(value);
        }

        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,uisv);
    }

    @Override
    public ReturnResultUtil queryEngineerPhoneByName(Long maintainerId, String engineerName) {
        Map map = new HashMap();
        map.put("maintainerId",maintainerId);
        map.put("engineerName",engineerName);
        String phone = upkeepDao.queryEngineerPhoneByName(map);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,phone);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil saveAssign(UpkeepView upkeep,User user) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        UpkeepView upkeep1 = upkeepDao.queryUpkeepInfo(upkeep);
        if(upkeep1 == null){
            return new ReturnResultUtil(500,MessageUtil.ASSIGNUPKEEPISNULL);
        }

    /*    if(upkeep1.getStatus() != null ){
            return new ReturnResultUtil(500,MessageUtil.UPKEEPALREADYASSIGN);
        }*/
        //插入指派信息
        Appoint appoint = new Appoint();
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        appoint.setKeyId(upkeep.getUpkeepId());
        appoint.setKeyType(2902L);
        appoint.setInstructedType(user.getType());
        appoint.setInstructedId(upkeep.getServiceId());
        appoint.setInstructedType(upkeep.getServiceType());
        appoint.setCreateTime(df.format(new Date()));
        appoint.setCreatePerson(user.getUserId());
        if(upkeep.getEngineerId() != null){
            appoint.setEngineerName(upkeep.getEngineerName());
            appoint.setEngineerPhone(upkeep.getEngineerPhone());
        }
        appointDao.insertSelective(appoint);

        Long serviceType = appoint.getInstructedType();
        Long instructedId = appoint.getInstructedId();
        String serviceName =queryServiceName(serviceType,instructedId);
        String serviceTypeName =queryServiceTypeName(serviceType);
        String str = upkeep1.getUpkeepApplicant() + "申请的设备-"+upkeep1.getDeviceName()+"保养，";
        //插入保养事件信息
        Event event1 = new Event();
        event1.setEventTitle("分配服务商");
        if(upkeep.getStatus() == 1801){
            str += "平台管理员的" + user.getRealName() +"已分配给"+serviceTypeName+"("+serviceName+")";
        }else{
            str += "平台管理员的" + user.getRealName() +"已分配给"+serviceTypeName+"("+serviceName+")"+"并指派给负责人-"+ upkeep.getEngineerName();
        }
        event1.setEventContent(str);
        event1.setEventId(UUIDGenerator.getUniqueLong());
        event1.setEventDateTime(df.format(new Date()));
        event1.setKeyType(1602L);
        event1.setKeyId(upkeep.getUpkeepId());
        event1.setCreatePerson(upkeep.getCreatePerson());
        event1.setCreateTime(df.format(new Date()));
        event1.setIsDel(0);
        eventDao.insertSelective(event1);

        if(upkeep1.getServiceId() == null){
            upkeep.setServiceContacts(null);
            upkeep.setServicePhone(null);
            upkeep.setServiceName(null);
            upkeep.setServiceType(null);
            upkeep.setServiceId(null);
        }

        upkeepDao.updateByPrimaryKeySelective(upkeep);

        new Thread(new ChatGroupThread(upkeep.getUpkeepId()+"",webSocket_InsertUpkeepUrl)).start();
        //发送短信
        new Thread(new DispatchSendSmsThread(upkeep.getUpkeepId(),2,userDao,null,upkeepDao,
                null,null,upkeepByService1,upkeepByEngineer1)).start();
        return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil saveComple(UpkeepView upkeep,User user) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        UpkeepView upkeep1 = upkeepDao.queryUpkeepInfo(upkeep);
        if(upkeep1 == null){
            return new ReturnResultUtil(500,MessageUtil.ASSIGNUPKEEPISNULL);
        }

        if(upkeep1.getStatus() != null && upkeep1.getStatus().longValue() != 1803){
            return new ReturnResultUtil(500,MessageUtil.UPKEEPCONFIRMYASSIGN);
        }

        int result = upkeepDao.updateByPrimaryKeySelective(upkeep);
        if(result > 0){
            Hospital hospital = hospitalDao.selectByPrimaryKey(user.getHospitalId());
            Event event1 = new Event();
            event1.setEventTitle("确认保养");
            String str = upkeep1.getUpkeepApplicant() + "申请的" + upkeep1.getDeviceName() + "保养,";

            if(user.getType() == 1104){
                if(upkeep.getStatus().longValue() == 1804){
                    str += "平台的已经确认保养";
                }else{
                    str += "平台的已经确认未保养";
                }
            }else{
                if(upkeep.getStatus().longValue() == 1804){
                    str +=  "医院的"+user.getRealName()+"已经确认保养";
                }else{
                    str +=  "医院的"+user.getRealName()+"已经确认未保养";
                }
            }

            event1.setEventContent(str);
            event1.setEventId(UUIDGenerator.getUniqueLong());
            event1.setEventDateTime(df.format(new Date()));
            event1.setKeyType(1602L);
            event1.setKeyId(upkeep.getUpkeepId());
            event1.setCreatePerson(upkeep.getCreatePerson());
            event1.setCreateTime(df.format(new Date()));
            event1.setIsDel(0);
            eventDao.insertSelective(event1);

            //退回流程
            if(upkeep.getStatus().longValue() == 1805){
                Upkeep upkeeps = upkeepDao.selectByPrimaryKey(upkeep1.getUpkeepId());
                upkeeps.setIsDel(1);
                Long oldUpkeepId = upkeep1.getUpkeepId();
                Long newUpkeepId = UUIDGenerator.getUniqueLong();
                Map map = new HashMap();
                map.put("oldUpkeepId",oldUpkeepId);
                map.put("newUpkeepId",newUpkeepId);
                int results = upkeepDao.updateUpkeepIdByCopy(map);
                if(results > 0){
                    Upkeep newUpkeep = new Upkeep();
                    newUpkeep.setIsDel(0);
                    newUpkeep.setUpkeepId(oldUpkeepId);
                    newUpkeep.setUpkeepDate(upkeep1.getUpkeepDate());
                    newUpkeep.setDeviceId(upkeep1.getDeviceId());
                    newUpkeep.setUpkeepNo(upkeep1.getUpkeepNo());
                    newUpkeep.setUpkeepApplicant(upkeep1.getUpkeepApplicant());
                    newUpkeep.setUpkeepApplicantPhone(upkeep1.getUpkeepApplicantPhone());
                    newUpkeep.setDeviceStatus(upkeep1.getDeviceStatus());
                    newUpkeep.setStatus(upkeep.getStatus());
                    newUpkeep.setHospitalId(upkeep1.getHospitalId());
                    newUpkeep.setCreateTime(upkeep1.getCreateTime());
                    newUpkeep.setCreatePerson(upkeep1.getCreatePerson());
                    upkeepDao.insertSelective(newUpkeep);
                }
                new Thread(new HospitalNotConfirmSmsThread(upkeep.getUpkeepId(),2,userDao,null,
                        upkeepDao,null,upkeepByPlatform2)).start();
            }
            //通过
            else{
                new Thread(new HospitalConfirmSmsThread(upkeep.getUpkeepId(),2,userDao,null,
                        upkeepDao,null,upkeepByService2)).start();
            }


        }
        return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil saveUpkeepData(UpkeepView upkeepView,User user) {
        UpkeepView upkeep1 = upkeepDao.queryUpkeepInfo(upkeepView);
        if(upkeep1 == null){
            return new ReturnResultUtil(500,MessageUtil.ASSIGNUPKEEPISNULL);
        }

        if(upkeep1.getStatus() != null && upkeep1.getStatus() != 1802){
            return new ReturnResultUtil(500,MessageUtil.UPKEEPCONFIRMYASSIGN);
        }

        DateFormat df  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int result = upkeepDao.updateByPrimaryKeySelective(upkeepView);
        if(result > 0){
            if(upkeepView.getFileList() != null && upkeepView.getFileList().size() > 0){
                for(FileView fileView : upkeepView.getFileList()){
                    fileView.setKeyId(upkeepView.getUpkeepId());
                    fileDao.updateByPrimaryKeySelective(fileView);
                }
            }

            if(upkeepView.getEndDeviceStatus() != null){ //修改设备状态
                Device device = new Device();
                device.setDeviceId(upkeep1.getDeviceId());
                device.setDeviceStatus(upkeepView.getEndDeviceStatus());
                device.setLastUpkeepDate(upkeepView.getUpkeepDate());
                deviceDao.updateByPrimaryKeySelective(device);
            }
            String str = upkeep1.getUpkeepApplicant() + "申请的设备-"+upkeep1.getDeviceName()+"保养，";

            Event event1 = new Event();  //绑定事件
            event1.setEventTitle("填写保养记录");


            if(user.getType() == 1104){
                str += "平台的" + user.getRealName() + "已填写保养信息";
            }else{
                String serviceTypeName = queryServiceTypeName(user.getType());
                Long serviceId = null;
                if(user.getType().longValue() == 1102){
                    serviceId = user.getManufacturerId();
                }else if(user.getType().longValue() == 1105){
                    serviceId = user.getSupplierId();
                }else if(user.getType().longValue() == 1103){
                    serviceId = user.getMaintainerId();
                }
                String serviceName = queryServiceName(user.getType(),serviceId);
                str += serviceTypeName + "("+serviceName+")"+"的"+user.getRealName() + "已填写保养信息";
            }
            event1.setEventContent(str);
            event1.setEventId(UUIDGenerator.getUniqueLong());
            event1.setEventDateTime(df.format(new Date()));
            event1.setKeyType(1602L);
            event1.setKeyId(upkeepView.getUpkeepId());
            event1.setCreatePerson(upkeepView.getCreatePerson());
            event1.setCreateTime(df.format(new Date()));
            event1.setIsDel(0);
            eventDao.insertSelective(event1);

            //推送
            new Thread(new EngineerDoSmsThread(upkeepView.getUpkeepId(),2,null,
                    upkeepDao,null,upkeepByHospital2)).start();
            return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEFAIL);
    }

    @Override
    public ReturnResultUtil queryDeviceIsUpkeep(Long deviceId) {
        int result = upkeepDao.queryDeviceIsUpkeep(deviceId);
        if(result>0){
            return new ReturnResultUtil(200,MessageUtil.DEVICEISUPKEEP,1);
        }
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil saveExamineMaintainer(Maintainer maintainer,Upkeep upkeep) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(upkeep.getExamine() == 1){
            Maintainer maintainer1 = maintainerDao.checkMaintainer(maintainer);
            if(maintainer1 == null ){
                maintainerDao.insertSelective(maintainer);
                upkeep.setServiceId(maintainer.getMaintainerId());
            }else{
                upkeep.setServiceId(maintainer1.getMaintainerId());
            }
        }
        int result = upkeepDao.updateByPrimaryKeySelective(upkeep);
        if(result > 0){
            UpkeepView upkeepView = upkeepDao.queryUpkeepInfo((UpkeepView)upkeep);
            Event event1 = new Event();
            event1.setEventTitle("审核维修商");
            String str = upkeepView.getUpkeepApplicant() + "-申请的" + upkeepView.getDeviceName()+"的保养平台审核";
            if(upkeep.getExamine() == 1){
                str +="通过，待维修商-"+maintainer.getMaintainerName()+"处理";
            }else if(upkeep.getExamine() == 2){
                str ="不通过，待平台重新指派";
            }
            event1.setEventContent(str);
            event1.setEventId(UUIDGenerator.getUniqueLong());
            event1.setEventDateTime(df.format(new Date()));
            event1.setKeyType(1602L);
            event1.setKeyId(upkeep.getUpkeepId());
            event1.setCreatePerson(upkeep.getCreatePerson());
            event1.setCreateTime(df.format(new Date()));
            event1.setIsDel(0);
            eventDao.insertSelective(event1);
        }

        Thread t = new Thread(new Runnable() {  //刷新缓存维修商
            @Override
            public void run() {
                try {
                    maintainerManufacturerInit.queryMaintainerManufacturer();
                    manufacturerInit.queryManufacturerMaintainer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();

        return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil assignServiceOrEngineer(Appoint appoint) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Upkeep upkeep = upkeepDao.selectByPrimaryKey(appoint.getKeyId());
        if(upkeep == null){
            return  new ReturnResultUtil(500,MessageUtil.ASSIGNUPKEEPISNULL);
        }
        if(appoint.getEngineerId() != null){
            upkeep.setStatus(1806L);
        }
        upkeep.setEngineerId(appoint.getEngineerId());
        int result = upkeepDao.updateByPrimaryKey(upkeep);
        if(result > 0){
            appoint.setAppointId(UUIDGenerator.getUniqueLong());
            appoint.setKeyType(2902L);
            appoint.setCreateTime(df.format(new Date()));
            int results = appointDao.insertSelective(appoint);
            if(results > 0){
                AppointView appointView = new AppointView(); //回写上条记录的响应时间。
                appointView.setInstructedType(appoint.getInstructType());
                appointView.setInstructedId(appoint.getInstructId());
                appointView.setKeyId(appoint.getKeyId());
                Appoint appoint1 = appointDao.queryLastAppoint(appointView);
                appoint1.setResponseTime(appoint.getCreateTime());
                appointDao.updateByPrimaryKey(appoint1);

                UpkeepView upkeepView = new UpkeepView();
                upkeepView.setUpkeepId(appoint.getKeyId());
                upkeepView = upkeepDao.queryUpkeepInfo(upkeepView);

                Event event1 = new Event();
                event1.setEventTitle("服务商指派");
                String str = upkeepView.getUpkeepApplicant() + "申请的设备-"+upkeepView.getDeviceName()+"保养，";

                String serviceTypeName1 = queryServiceTypeName(appoint.getInstructType());
                String serviceName1 = queryServiceName(appoint.getInstructType(),appoint.getInstructId());
                String serviceTypeName2 = queryServiceTypeName(appoint.getInstructedType());
                String serviceName2 = queryServiceName(appoint.getInstructedType(),appoint.getInstructedId());

                if(appoint.getEngineerId() == null && appoint.getInstructedId().longValue() != appoint.getAppointId().longValue()){
                    str+= serviceTypeName1 + "("+serviceName1+")"+"指派给"+ serviceTypeName2 + "("+serviceName2+")";
                }else if(appoint.getEngineerId() != null && appoint.getInstructedId().longValue() != appoint.getAppointId().longValue() ){
                    str+= serviceTypeName1 + "("+serviceName1+")"+"指派给"+ serviceTypeName2 + "("+serviceName2+"),并指派工程师-" + appoint.getEngineerName();
                }else if(appoint.getEngineerId() != null && appoint.getInstructedId().longValue() != appoint.getAppointId().longValue() ){
                    str+= serviceTypeName1 + "("+serviceName1+")"+"指派给工程师-" + appoint.getEngineerName();
                }
                event1.setEventContent(str);
                event1.setEventId(UUIDGenerator.getUniqueLong());
                event1.setEventDateTime(df.format(new Date()));
                event1.setKeyType(1602L);
                event1.setKeyId(upkeep.getUpkeepId());
                event1.setCreatePerson(upkeep.getCreatePerson());
                event1.setCreateTime(df.format(new Date()));
                event1.setIsDel(0);
                eventDao.insertSelective(event1);

                new Thread(new ChatGroupThread(upkeep.getUpkeepId()+"",webSocket_InsertUpkeepUrl)).start();
                //发送短信
                new Thread(new DispatchSendSmsThread(upkeep.getUpkeepId(),2,userDao,null,upkeepDao,
                        null,null,upkeepByService1,upkeepByEngineer1)).start();

                return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
            }
        }
        return new ReturnResultUtil(500,MessageUtil.SENDFAIL);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil updateEngineerNameAndEngineerPhone(Appoint appoint,User loginUser) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Appoint appoint1 = appointDao.selectByPrimaryKey(appoint.getAppointId());
        appoint.setInstructedId(appoint1.getInstructedId());
        appoint.setInstructedType(appoint1.getInstructedType());
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        appoint.setKeyId(appoint1.getKeyId());
        appoint.setKeyType(appoint1.getKeyType());
        appoint.setCreateTime(df.format(new Date()));
        appoint.setAppointId(UUIDGenerator.getUniqueLong());
        ReturnResultUtil rru = userService.queryUserByEngineerPhone(appoint.getEngineerPhone(),appoint.getEngineerName(),appoint.getInstructedId(),appoint.getInstructedType());
        if(rru.getRet() == 500){
            return rru;
        }
        User user = (User) rru.getData();
        appoint.setEngineerId(user.getUserId());
        if(loginUser.getType().longValue() == 1104){
            appoint.setInstructId(null);
            appoint.setInstructType(loginUser.getType());
        }else{
            appoint.setInstructId(appoint1.getInstructedId());
            appoint.setInstructType(appoint1.getInstructedType());
        }

        int result = appointDao.insertSelective(appoint);
        if(result > 0){
            Upkeep upkeep = upkeepDao.selectByPrimaryKey(appoint1.getKeyId());
            upkeep.setEngineerId(appoint.getEngineerId());
            upkeep.setStatus(1806L);
            upkeepDao.updateByPrimaryKey(upkeep);

            new Thread(new UpdateEngineerSmsThread(appoint1.getKeyId(),2,null,
                    upkeepDao,null,upkeepByEngineer1)).start();

            return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
        }
        return new ReturnResultUtil(500,MessageUtil.SENDFAIL);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil dxpectedToDoorByEngineer(Upkeep upkeep) {
        Upkeep upkeep1 = upkeepDao.selectByPrimaryKey(upkeep.getUpkeepId());
        if(upkeep1 == null){
            return new ReturnResultUtil(500,MessageUtil.ASSIGNUPKEEPISNULL);
        }
        int result  = upkeepDao.updateByPrimaryKeySelective(upkeep);
        if(result > 0){
            new Thread(new EngineerResponseSmsThread(upkeep.getUpkeepId(),2,null,
                    upkeepDao,null,upkeepByHospital1)).start();
            return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEFAIL);
    }

    @Override
    public ReturnResultUtil remindUpkeepList(Map map) {
        List<UpkeepView> list = upkeepDao.remindUpkeepList(map);
        list = queryCurrentService(list);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,list);
    }

    @Override
    public ReturnResultUtil queryPhoneByHospital(Map map) {
        List<Map> list = upkeepDao.queryPhoneByHospital(map);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,list);
    }


    //发送信息给大屏socket
    public void sendUkeepMessageBySocket(UpkeepView upkeepView){
        UpkeepView upkeep = upkeepDao.queryUpkeepInfo(upkeepView);
        SocketMessageView smv = new SocketMessageView();
        smv.setMessageType("body");
        smv.setType(3);
        smv.setMessage(upkeep.getHospitalName()+"对设备-" + upkeep.getDeviceName() + "。申请了一条保养信息。");
        WSClientManager.sendMessage(JSON.toJSONString(smv));
    }
}
